package com.piece.file.filter;

import com.piece.core.framework.enums.WebFilterOrder;
import com.piece.core.web.filter.FilterHook;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

@Slf4j
@Component
public class ChinesePathFilter implements FilterHook {

    @Override
    public void initFilter() {
    }

    @Override
    public String[] getFilterPath() {
        return new String[]{"/office"};
    }

    @Override
    public Integer getIndex() {
        return WebFilterOrder.XSS_FILTER + 10;
    }

    @Override
    public Pair beforeFilter(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            StringBuilder pathBuilder = new StringBuilder();
            pathBuilder.append(request.getScheme()).append("://").append(request.getServerName()).append(":")
                    .append(request.getServerPort()).append(request.getContextPath()).append("/");
            request.setAttribute("baseUrl", pathBuilder.toString());
            return Pair.of(request, response);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void afterFilter(HttpServletRequest request, HttpServletResponse response)  {
    }
}
